<template>
    <d2-container>
        <div style="margin-bottom: 40px">
            <a href="#/douyinAccount/changedouyinAccount">
                <el-button type="primary" style="float:right" icon="el-icon-plus" size="mini">新建账号</el-button>
            </a>
        </div>
        <el-table :data="dataList" border style="width: 100%">

            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="cellphone" label="手机"></el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button @click="detailClick(scope.row)" type="text" size="small">查看详情</el-button>
                    <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background layout="total,sizes,prev, pager, next,jumper" :page-size="pageSize"
            :current-page="currentPage" :total="total" @current-change="handleCurrentChange"
            @size-change="handlerSizeChange" @next-click="handleNextPage" @prev-click="handlePrevClick"></el-pagination>
    </d2-container>
</template>

<script>
import request from "@/plugin/axios";
import { mapState } from "vuex";
import excel from "@/libs/util.excel"

export default {
    data() {
        return {
            dataList: [],
            total: 0,
            pageSize: 10,
            currentPage: 1,
            classroom: [],
            dataSearch: {},
            schoolList: [],
            school: undefined,
            departmentList: [],
            department: undefined,
            cellphone: undefined,
            name: undefined,
            disabled: false,
            schoolLimit: undefined,
            headquarter: 0

        };
    },
    computed: {
        ...mapState('d2admin/user', ['info']),
    },
    methods: {
        formSubmit() {
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDataList(this.dataSearch);
        },
        formReset() {
            this.dataSearch = {}
            this.getDataList(this.dataSearch)
        },
        detailClick(e) {
            this.$router.push({ path: "/douyinAccount/changedouyinAccount?id=" + e._id });
        },
        schoolSelected() {
            this.dataSearch.department = undefined
            this.getDepartmentList(1, 99999, this.dataSearch.school);
        },

        handleCurrentChange(currentPage) {
            this.currentPage = currentPage;
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDataList(this.dataSearch);
        },
        handlerSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDataList(this.dataSearch);
        },
        handleNextPage() {
            this.currentPage = this.currentPage + 1;
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDataList(this.dataSearch);
        },
        handlePrevClick() {
            this.currentPage = this.currentPage - 1;
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDataList(this.dataSearch);
        },
        deleteClick(e) {
            this.$confirm("此操作将删除账号, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                request({
                    url: "/message/deleteDouyinAccount",
                    method: "post",
                    data: { id: e._id }
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "删除成功"
                        });
                        this.getDataList(this.dataSearch);
                    }
                });
            })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },
        getSchoolList(page, pageSize) {
            let data = {};
            data.page = 1
            data.pageSize = 999999
            request({
                url: "/school/getSchoolList",
                method: "post",
                data
            }).then(res => {
                this.schoolList = res.data.school;
                // 返回数据
            });
        },
        getDepartmentList(page, pageSize, school) {
            let data = {};
            (data.page = page), (data.pageSize = pageSize), (data.school = school);
            request({
                url: "/department/getDepartmentList",
                method: "post",
                data
            }).then(res => {
                this.departmentList = res.data.department;
                // 返回数据
            });
        },

        getDataList() {
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            request({
                url: "/message/getDouyinAccountList",
                method: "post",
                // data: this.dataSearch
            }).then(res => {
                this.dataList = res.data.data;
                this.total = res.data.total;
                this.currentPage = res.data.currentPage;
            });
        },

        downloadTemplate() {

            excel.export([{ label: '名字', prop: 'name' }, { label: '性别', prop: 'gender' }, { label: '生日', prop: 'birthday' }, { label: '手机', prop: 'cellphone' }, { label: '地址', prop: 'address' }, { label: '部门', prop: 'department' }, { label: '职务', prop: 'position' }, { label: '入职日期', prop: 'entryDate' }], [{ name: '张三', gender: '0（0-男，1-女)', birthday: '2010.02.02(必须用“.”分隔)', cellphone: '13501234567', department: '教学组(名字必须正确，否则无法导入)', position: '教务(名字必须正确，否则无法导入)', address: '张哈路1111号', entryDate: '2010.02.02(必须用“.”分隔)' }], '员工批量导入模板')
            // this.$export.excel({
            //     columns: [{label:'名字',prop:'name'},{label:'性别',prop:'gender'},{label:'生日',prop:'birthday'},{label:'手机',prop:'cellphone'},{label:'地址',prop:'address'},{label:'部门',prop:'department'},{label:'入职日期',prop:'entryDate'}],
            //     data: [{name:'张三',gender:'0（0-男，1-女)',birthday:'2010.02.02(必须用“.”分隔)',cellphone:'13501234567',department:'教学组(名字必须正确，否则无法导入)',address:'张哈路1111号',entryDate:'2010.02.02(必须用“.”分隔)'}],
            //     title : '员工批量导入模板'
            // })
            //     .then(() => {
            //         this.$message('导出表格成功')
            //     })
        },

        exportList() {
            let school;
            let _class;
            let data = {}

            if (this.school.headquarter != 1) {
                this.dataSearch.school = this.info.school.map(value => value._id);
                data.school = this.dataSearch.school;
            }



            data.page = 1
            data.pageSize = 999999
            const loading = this.$loading({
                lock: true,
                text: '',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            request({
                url: "/staff/getStaffList",
                method: "post",
                data: data
            }).then(res => {
                loading.close()
                // if (res.code == 200){
                //     this.$alert('','下载成功')
                // }

                if (res.code == 200) {
                    let temp = []
                    temp = res.data.staff;
                    temp.forEach((item, index) => {
                        temp[index].position = item.position == undefined ? '' : item.position.name
                        temp[index].reportTarget = item.reportTarget == undefined ? '' : item.reportTarget.map(value => value.name).join(',');
                        temp[index].class = item.class == undefined ? '' : item.class.map(value => value.name).join(',');
                        temp[index].school = item.school == undefined ? '' : item.school.map(value => value.name).join(',');

                        temp[index].gender = item.gender == 0 ? '男' : '女';
                        temp[index].department = item.department == undefined ? '' : item.department.name;
                        // temp[index].entryDate = item.entryDate == undefined ? '' : new Date(entryDate)

                    });
                    excel.export([{ label: '姓名', prop: 'name' }, { label: '性别', prop: 'gender' }, { label: '校区', prop: 'school' }, { label: '手机', prop: 'cellphone' }, { label: '职位', prop: 'position' }, { label: '生日', prop: 'birthday' }, { label: '入职日期', prop: 'entryDate' }, { label: '部门', prop: 'department' }, { label: '地址', prop: 'address' }], temp, '员工列表')

                    // this.$export.excel({
                    //     columns: [{label:'姓名',prop:'name'},{label:'性别',prop:'gender'},{label:'校区',prop:'school'},{label:'手机',prop:'cellphone'},{label:'职位',prop:'position'},{label:'生日',prop:'birthday'},{label:'入职日期',prop:'entryDate'},{label:'部门',prop:'department'},{label:'地址',prop:'address'}],
                    //     data: temp,
                    //     title : '员工列表'
                    // })
                }




            })

        },

        uploadTemplate(file) {

            let thisFile = event.currentTarget.files[0]
            var rABS = false; //是否将文件读取为二进制字符串  
            const that = this
            FileReader.prototype.readAsBinaryString = function (f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串  
                var pt = this;
                var workbook; //读取完成的数据  
                // var excelData;  
                var reader = new FileReader();
                reader.onprogress = function (e) {
                    let total = thisFile.size;
                    this.progress = (e.loaded / total) * 100;
                    console.log(this.progress);
                };
                reader.onload = function (e) {
                    // var XLSX = require('xlsx');
                    try {
                        var bytes = new Uint8Array(reader.result);
                        var length = bytes.byteLength;
                        for (var i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        if (rABS) {
                            workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
                                type: 'base64'
                            });
                        } else {
                            workbook = XLSX.read(binary, {
                                type: 'binary'
                            });
                        }
                        // excelData = []; 
                    } catch (e) {
                        console.log('文件类型不正确', e);
                        return;
                    }
                    let tempData = []
                    var fromTo = '';
                    for (var sheet in workbook.Sheets) {
                        if (workbook.Sheets.hasOwnProperty(sheet)) {
                            fromTo = workbook.Sheets[sheet]['!ref'];
                            let temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
                            for (var i = 0; i < temp.length; i++) {
                                let xxx = {}
                                xxx.name = temp[i]['名字']
                                xxx.cellphone = temp[i]['手机']
                                xxx.gender = temp[i]['性别']
                                xxx.birthday = temp[i]['生日']
                                xxx.entryDate = temp[i]['入职日期']
                                xxx.addrss = temp[i]['地址']
                                xxx.department = temp[i]['部门']
                                xxx.position = temp[i]['职务']
                                if ((parseInt(xxx.gender) != 0) && (parseInt(xxx.gender) != 1)) {
                                    that.$alert('0为男，1为女', '性别请填0或1')
                                    return false
                                }
                                if (new Date(xxx.birthday) == 'Invalid Date') {
                                    that.$alert('生日日期错误', '信息错误')
                                    return false
                                }
                                if (new Date(xxx.entryDate) == 'Invalid Date') {
                                    that.$alert('入职日期错误', '信息错误')
                                    return false
                                }

                                tempData.push(xxx);
                            }




                        }
                    }
                    let data = {}
                    data.data = tempData
                    data.school = that.school._id
                    const loading = that.$loading({
                        lock: true,
                        text: '',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    })
                    request({
                        url: "/staff/importStaff",
                        method: "post",
                        data: data
                    }).then(res => {
                        loading.close()
                        if (res.code == 200) {
                            that.$alert('', '导入成功！')
                            that.getDataList()


                        }
                    })

                };

                reader.readAsArrayBuffer(f);

            }

            var reader = new FileReader();
            if (rABS) {
                reader.readAsArrayBuffer(thisFile);
            } else {
                reader.readAsBinaryString(thisFile);
            }


        },
    },

    created() {
            this.getDataList();
    }
};
</script>
